#include <LinkList.h>

// head insert
LinkList List_HeadInsert(LinkList &L) {
    LNode *s; int x;
    // create head node
    L = (LinkList) malloc(sizeof(LNode));
    L->next = NULL;

    scanf("%d", &x);
    while (x != 9999) {
       // create a new node
       s = (LNode) malloc(sizeof(LNode));
       s->data = x;
       // insert node
       s->next = L->next; 
       L->next = s;

       scanf("%d", &x);
    }
    return L;
}

// tail insert
LinkList List_TailInsert(LintList &L) {
    int x;
    // create head node
    L = (LinkList) malloc(sizeof(LNode));
    L->next = NULL;
    
    LNode *s, *r=L;
    scanf("%d", &x);
    while(x != 9999) {
        // create a new node
        s = (LNode *) malloc(sizeof(LNode));
        s->data = x;

        // insert
        r->next = s;
        r = s;  // tail point to s
        
        scanf("%d", &x);
    }
    r->next = NULL; // 
    return L;
}

// get value of element by i
LNode *GetElem (LinkList L, int i) {
    int j = 1; // start from 1
    LNode *p = L->next; // head node
    if (i == 0)
        return L;
    if (i < 1)
        return NULL;

    // move to 'i'
    while (p && j<i) {
        p = p->next;
        j++;
    }
    return p;
}

// locate element by value
LNode *LocateElem(LinkList L, ElemType e) {
    LNode *p = L->next; // head node

    while (p != NULL && p->data != e)
        p = p->next;

    return p;
}

// insert (at back)
void InsertElem(LinkList &L, LNode &s, int i) {
    LNode *p = GetElem(L, i-1);
    s->next = p->next;
    p->next = s;
}

// delete
void DeleteElem(LinkList &L, int i) {
    LNode *p = GetElem(L, i-1);
    LNode *q = p->next;
    p->next = q->next; // delete
    free(q);
}

